package com.moinut.studentattendancemanager.controller;

import com.moinut.studentattendancemanager.UserManager;
import com.moinut.studentattendancemanager.config.UserType;
import com.moinut.studentattendancemanager.model.factory.DAOFactory;
import com.moinut.studentattendancemanager.model.vo.db.Student;
import com.moinut.studentattendancemanager.model.vo.db.Teacher;
import com.sun.istack.internal.NotNull;

/**
 * @author MOILING
 */
public class LoginController {

    public interface OnLoginListener {
        void onLoginSuccess();

        void onLoginError(String error);
    }

    public static void login(@NotNull String id, @NotNull String password, @NotNull UserType type, @NotNull OnLoginListener listener) {
        if (id.isEmpty()) {
            listener.onLoginError("账号不能为空");
        } else if (password.isEmpty()) {
            listener.onLoginError("密码不能为空");
        } else if (type == UserType.TYPE_STUDENT) {
            try {
                if (DAOFactory.getIStudentDAOInstance().findLogin(new Student(id, password)) != null) {
                    UserManager.setStudent(id);
                    listener.onLoginSuccess();
                } else {
                    listener.onLoginError("账号/密码错误");
                }
            } catch (Exception e) {
                e.printStackTrace();
                listener.onLoginError(e.getMessage());
            }
        } else if (type == UserType.TYPE_TEACHER) {
            try {
                if (DAOFactory.getITeacherDAOInstance().findLogin(new Teacher(id, password)) != null) {
                    UserManager.setTeacher(id, false);
                    listener.onLoginSuccess();
                } else {
                    listener.onLoginError("账号/密码错误");
                }
            } catch (Exception e) {
                e.printStackTrace();
                listener.onLoginError(e.getMessage());
            }
        }

    }
}
